<template>
  <el-main>
    <h1 style="margin-bottom: 20px">{{ this.id ? '编辑分类' : '新建分类'}}</h1>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="上级分类">
          <el-select v-model="form.parent" placeholder="请选择">
            <el-option 
              v-for="option in parentOptions"
              :key="option._id"
              :label="option.name" 
              :value="option._id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="分类名称">
            <el-input v-model="form.name"></el-input>
        </el-form-item>
        
        <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-main>
</template>
<script>
  export default {
    props: {
      id: {type: String}
    },
    data() {
      return {
        form: {
          name: '',
          parent: '',
        },
        parentOptions: []
      }
    },
    created() {
      this.id && this.fetch()
      this.fetchParents()
    },
    methods: {
      async onSubmit() {
        let res
        if(this.id) {
          res = await this.$http.put(`curd/category/${this.id}`, this.form)
        } else {
          res = await this.$http.post('curd/category', this.form)
        }
        if(res.data.code === 200) {
          this.$message({
            message: '保存成功！',
            type: 'success'
          });
          this.$router.push('/category/list')
        }
      },
      async fetch() {
        const res = await this.$http.get(`curd/category/${this.id}`)
        this.form = res.data
      },
      async fetchParents() {
        const res = await this.$http.get(`curd/category`)
        console.log('res :>> ', res);
        this.parentOptions = res.data
      }
    }
  }
</script>